
package ca.etsmtl.logti.log619.lab05.filter;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.mail.internet.MimeMessage;

public class SpamhausAddressFilter implements EmailFilter {

    @Override
    public String getFilterName() {
        return getClass().getSimpleName();
    }

    @Override
    public byte checkSpam(MimeMessage message) {
        try {
            @SuppressWarnings("unchecked")
			Enumeration<String> lines = message.getAllHeaderLines();
            while (lines.hasMoreElements()) {
                String line = lines.nextElement();
                String ip = extractIP(line);
                if (ip != null) {
                    if (!ip.startsWith("192.168")) {
                        if (lookup(ip, "sbl.spamhaus.org") || 
                        	lookup(ip, "xbl.spamhaus.org") || 
                        	lookup(ip, "pbl.spamhaus.org")) {
                            return 100;
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return 0;
    }

    public String extractIP(String line) {

        int pos;
        String ip;

        // try ([n.n.n.n])
        if ((pos = line.indexOf("[")) > 0) {
            ip = line.substring(pos + 1);

            if ((pos = ip.indexOf("]")) > 0) {
                ip = ip.substring(0, pos);
            }
            return ip;
        }
        return null;
    }

    private String reverseOctets(String octets) {
        StringTokenizer st = new StringTokenizer(octets, ".");

        String res = "";
        while (st.hasMoreTokens()) {
            res = st.nextToken() + "." + res;
        }

        return res;
    }

    private boolean lookup(String name, String domain) {
        // reverse the name
        String reverseName = reverseOctets(name);

        if (reverseName.length() == 0)
            return false;

        reverseName += domain;

        try {
            InetAddress[] hits = InetAddress.getAllByName(reverseName);
            if (hits != null && hits.length > 0) {
                return true;
            }
        } catch (UnknownHostException ex) {
            return false;
        }
        return false;
    }

    @Override
    public boolean enabled() {
        return true;
    }

    @Override
    public byte getConfidenceLevel() {
        return 100;
    }
}
